package com.example.yimai.service.impl;

import com.example.yimai.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 图形验证码过期时间（分钟）
    private static final long IMAGE_CAPTCHA_EXPIRATION = 1;

    @Override
    public void generateCaptchaImage(HttpServletResponse response, String key) throws Exception {
        int width = 120;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 生成随机验证码
        String captcha = generateRandomCaptcha(4);
        
        // 将验证码存入Redis
        String redisKey = "captcha:image:" + key;
        redisTemplate.opsForValue().set(redisKey, captcha, IMAGE_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 24));
        g.setColor(Color.BLACK);
        
        // 绘制验证码
        int x = 20;
        for (char c : captcha.toCharArray()) {
            g.drawString(String.valueOf(c), x, 30);
            x += 20;
        }
        
        // 添加干扰线
        Random random = new Random();
        g.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        g.dispose();
        
        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        
        // 输出图片到客户端
        ImageIO.write(image, "png", response.getOutputStream());
    }

    @Override
    public boolean verifyCaptcha(String key, String captcha) {
        // 验证图形验证码
        String redisKey = "captcha:image:" + key;
        String storedCaptcha = redisTemplate.opsForValue().get(redisKey);
        
        if (storedCaptcha != null && storedCaptcha.equalsIgnoreCase(captcha)) {
            // 验证成功后删除验证码
            redisTemplate.delete(redisKey);
            return true;
        }
        
        return false;
    }

    /**
     * 生成随机验证码
     * @param length 验证码长度
     * @return 随机验证码
     */
    private String generateRandomCaptcha(int length) {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            captcha.append(chars.charAt(random.nextInt(chars.length())));
        }
        return captcha.toString();
    }
}